package com.szjlc.responsebodyadvice.interception;

import com.szjlc.responsebodyadvice.result.BusinessResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 响应结果拦截器
 * ResponseBodyAdvice是对Controller返回的内容在HttpMessageConverter中做类型转换之前拦截，
 * 进行相应的处理操作后，再将结果返回给客户端。这样就可以把统一包装的工作放到这个类里面。
 * @author steve
 * @since 2022-11-19 15:19
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.szjlc.responsebodyadvice")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    /** 判断是否要交给 beforeBodyWrite 方法执行，ture：需要；false：不需要 */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> clazz) {
        // 如果不需要进行封装的，可以添加一些校验手段，比如添加标记排除的注解
        return true;
    }

    /** 见名知意，返回值写入前对 response 进行具体的处理 */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 提供一定的灵活度，如果body已经被包装了，就不进行包装
        if (body instanceof BusinessResult) {
            return body;
        }

        if (body instanceof String) {
            log.debug("the response is String,body:{}", body);
            // return this.objectMapper.writeValueAsString(BusinessResult.success(body));
        }
        return BusinessResult.success(body);
    }
}
